﻿using Sustainalytics.Entities.ProductInvolvement;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.ProductInvolvement.Service.Models
{
    public class ProductInvolvementFrameworkCategoryDto
    {
        public string Symbol { get; set; }
        public string CategoryOfInvolvement { get; set; }
        public string CategorySymbol { get; set; }
        public int MaxValue { get; set; }
        public int SelectedValue { get; set; }
        public bool IsSignificantOwnership { get; set; }
        public bool SignificantOwnershipYesNo { get; set; }
        public bool RevenueRangeYesNo { get; set; }
        public bool IsInvolved { get; set; }
        public List<PIRangeDto> RevenueRange { get; set; }
        private ProductInvolvementFrameworkCategoryDto() { }
        public Guid TemplateCriteriaId { get; set; }

        public static ProductInvolvementFrameworkCategoryDto CreateComplete(ProductInvolvementCategory category, Guid templateCriteriaId)
        {
            List<PIRangeDto> revenueRange = new List<PIRangeDto>();
            if (category.RevenueRangeYesNo && category.RevenueRange.Any(rr => !rr.Value.NA))
                revenueRange = category.RevenueRange.Values.ToList().ConvertAll<PIRangeDto>(rr => PIRangeDto.CreateComplete(rr));
            
            
            return new ProductInvolvementFrameworkCategoryDto()
            {
                CategoryOfInvolvement = category.CategoryOfInvolvement,
                SignificantOwnershipYesNo = category.OwnershipYesNo,
                RevenueRangeYesNo = category.RevenueRangeYesNo,
                RevenueRange = revenueRange,
                MaxValue = GetMaxValueFromRevenueRange(category.RevenueRange.Values.ToList()),
                CategorySymbol = category.Symbol,
                TemplateCriteriaId = templateCriteriaId
            };
        }


        public static int GetMaxValueFromRevenueRange(List<PIRange> piRange)
        {
            var lastPIRange = piRange.OrderBy(rr => rr.RangeId).LastOrDefault(rr => rr.NA);
            if (lastPIRange != null)
                return 5 - lastPIRange.RangeId;

            return 5;
        }
    }

    public class PIRangeDto
    {
        public int RangeId { get; set; }
        public bool NA { get; set; }
        public double Start { get; set; }
        public double Stop { get; set; }

        private PIRangeDto() { }

        public static PIRangeDto CreateComplete(PIRange range)
        {
            if (range == null)
                throw new ArgumentNullException("PIRange", "The PIRange cannot be null.");

            return new PIRangeDto()
            {
                RangeId = range.RangeId,
                NA = range.NA,
                Start = range.Start,
                Stop = range.Stop
            };
        }
    }
}
